//
//  utility.c
//  FastPRDemo
//
//  Created by fanwenjie on 2017/6/6.
//  Copyright © 2017年 fanwenjie. All rights reserved.
//

#include <stdio.h>
///裁剪图片
void CropImage(const unsigned char *src, unsigned char *dst, short srcWidth, short dstWidth, short dstHeight, short x, short y)
{
    for(int i = 0; i < dstHeight; ++i)
        for(int j = 0;j < dstWidth; ++j)
        {
            dst[i * dstWidth + j] = src[(i + y) * srcWidth + j + x];
        }
}
///缩放图片
void ImageResize(const unsigned char *srcImage, const short srcWidth,const short srcHeight,const short desWidth,const short desHeight,unsigned char *desImage)
{
    int iSrc1[desWidth],iSrc2[desWidth];
    int iW1[desWidth],iW2[desWidth];
    const unsigned int area = ((unsigned int)desHeight) * desWidth;
    for(int i = 0;i < desWidth; ++i)
    {
        int value = i * srcWidth;
        iSrc1[i] = value / desWidth;
        iW2[i] = value % desWidth;
        iW1[i] = desWidth - iW2[i];
        iSrc2[i] = iSrc1[i] + (iW2[i] != 0);
    }
    
    for(int j = 0;j < desHeight; ++j)
    {
        int value = j * srcHeight;
        int jSrc1 = value / desHeight;
        int jw2 = value % desHeight;
        const unsigned char *srcj1 = srcImage + srcWidth * jSrc1;
        unsigned char *desj1 = desImage + j*desWidth;
        if(jw2){
            int jw1 = desHeight - jw2;
            const unsigned char *srcj2 = srcj1 + srcWidth;
            for(int i = 0;i < desWidth; ++i)
            {
                int iw1 = iW1[i], iw2 = iW2[i];
                int i1 = iSrc1[i],i2 = iSrc2[i];
                desj1[i] = (jw1 * (srcj1[i1] * iw1 + srcj1[i2] * iw2) + jw2 * (srcj2[i1] * iw1 + srcj2[i2] * iw2)) / area;
            }
        }else {
            for(int i = 0;i < desWidth; ++i)
            {
                int iw1 = iW1[i], iw2 = iW2[i];
                int i1 = iSrc1[i],i2 = iSrc2[i];
                desj1[i] = (srcj1[i1] * iw1 + srcj1[i2] * iw2) / desWidth;
            }
        }
    }
}

void Dilate(unsigned char *src, unsigned char *dst, const int rows, const int cols)
{
    const int TOP = -cols, RIGHT = 1, BOTTOM = cols, LEFT = -1;
    const int orient[] = { TOP + LEFT,TOP,TOP + RIGHT,RIGHT,BOTTOM + RIGHT,BOTTOM,BOTTOM + LEFT,LEFT };
    dst += RIGHT + BOTTOM;
    src += RIGHT + BOTTOM;
    for (int i = 0; i < rows - 2; ++i)
    {
        for (int j = 0; j < cols - 2; ++j)
        {
            unsigned char max = *src;
            for (int k = 0; k < sizeof(orient) / sizeof(*orient); ++k)
            {
                if (src[orient[k]] > max)
                    max = src[orient[k]];
            }
            *dst++ = max;
            ++src;
        }
        dst += 2;
        src += 2;
    }
}

